package com.noble.glamour.ui.mail.chat;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.noble.glamour.R;
import com.noble.glamour.bean.center.user.detail.UserDetail;
import com.noble.glamour.bean.center.user.light.UserLight;
import com.noble.glamour.bean.my.ChatInfo;
import com.noble.glamour.bean.my.GiftMessageList;
import com.noble.glamour.module.local.msgview.ChatViewLayout;
import com.noble.glamour.module.local.msgview.chatview.ChatInterface;
import com.noble.glamour.module.logic.application.ModuleMgr;
import com.noble.glamour.module.logic.config.Constant;
import com.noble.glamour.module.logic.request.HttpResponse;
import com.noble.glamour.module.logic.request.RequestComplete;
import com.noble.glamour.module.util.UIShow;
import com.noble.library.utils.UIUtil;
import com.noble.glamour.ui.user.my.view.GiftMessageInfoView;
import com.noble.glamour.ui.user.util.CenterConstant;
import com.noble.glamour.ui.user.util.OffNetPanel;
import com.noble.library.base.BaseActivity;
import com.noble.library.log.PLogger;
import com.noble.library.log.PSP;
import com.noble.library.observe.MsgMgr;
import com.noble.library.observe.MsgType;
import com.noble.library.observe.PObserver;
import com.noble.library.utils.InputUtils;
import com.noble.library.utils.ScreenUtils;
import com.noble.library.view.roadlights.LMarqueeFactory;
import com.noble.library.view.roadlights.LMarqueeView;
import com.noble.mail.type.MailSpecialID;

import java.util.List;

/**
 * 聊天页
 */
public class PrivateChatAct extends BaseActivity implements PObserver {

    private long whisperID = 0;
    private String name;
    private int kf_id;
    private ChatViewLayout privateChat = null;
    private TextView base_title_title, net_top_title;

    // 礼物跑马灯
    private LMarqueeView lmvMeassages;
    private LMarqueeFactory<LinearLayout, GiftMessageList.GiftMessageInfo> marqueeView;

    private OffNetPanel offNetPanel;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setCanNotify(false);//设置该页面不弹出悬浮窗消息通知
        setContentView(R.layout.p1_privatechatact);
        whisperID = getIntent().getLongExtra("whisperID", 0);
        name = getIntent().getStringExtra("name");
        kf_id = getIntent().getIntExtra("kf_id", -1);

        initView();
        MsgMgr.getInstance().attach(this);

        ModuleMgr.getPhizMgr().reqCustomFace();
        checkIsCanSendMsg();
    }

    private void checkIsCanSendMsg() {
        UserDetail userDetail = ModuleMgr.getCenterMgr().getMyInfo();

        //缘分小秘书
        if (MailSpecialID.customerService.getSpecialID() == whisperID) {
            privateChat.setInputGiftviewVisibility(View.GONE);
            boolean canEdit;
            canEdit = ModuleMgr.getCommonMgr().getCommonConfig().getCommon().canSecretaryShow() || userDetail.isVip();
            if (canEdit) {
                privateChat.getChatAdapter().showIsCanChat(true);//输入框显示
            } else {
                privateChat.getChatAdapter().showInputGONE();//输入框不显示
            }
            return;
        }

        if (!userDetail.isMan() || ModuleMgr.getChatListMgr().getTodayChatShow()
                || (userDetail.isVip())
                || userDetail.isVip()) {
            privateChat.getChatAdapter().showIsCanChat(true);
        } else {
            privateChat.getChatAdapter().showIsCanChat(false);
            InputUtils.HideKeyboard(privateChat);
        }
    }

    /**
     * 聊天窗口信息--整合接口
     */
    private void reqChatInfo() {

        //缘分小秘书
        UserDetail userDetail = ModuleMgr.getCenterMgr().getMyInfo();
        if (MailSpecialID.customerService.getSpecialID() == whisperID) {
            privateChat.setInputGiftviewVisibility(View.GONE);
            if (ModuleMgr.getCommonMgr().getCommonConfig().getCommon().canSecretaryShow() || userDetail.isVip()) {
                privateChat.getChatAdapter().showIsCanChat(true);//输入框显示
            } else {
                privateChat.getChatAdapter().showInputGONE();//输入框不显示
            }
            return;
        }
        privateChat.getChatAdapter().setTUID(whisperID);

        ModuleMgr.getCommonMgr().reqChatInfo(whisperID, new RequestComplete() {
            @Override
            public void onRequestComplete(HttpResponse response) {
                if (!response.isOk()) {
                    PLogger.e("获取会话信息失败!");
                    return;
                }
                ChatInfo chatInfo = (ChatInfo) response.getBaseData();
                ModuleMgr.getCenterMgr().getMyInfo().setDiamondsSum(chatInfo.getDiamond());

                //在线状态
                if (chatInfo.getOtherInfo().is_online()) {
                    net_top_title.setText(getString(R.string.net_online_pre) + chatInfo.getOtherInfo().netTp2Str(chatInfo.getOtherInfo().getNet_tp()));
                } else {
                    net_top_title.setText(getString(R.string.net_offline));
                }
            }
        });
    }

    /**
     * 礼物跑马灯数据
     */
    private void initLastGiftList() {
        if (MailSpecialID.customerService.getSpecialID() != whisperID)
            ModuleMgr.getCommonMgr().lastGiftList(new RequestComplete() {
                @Override
                public void onRequestComplete(HttpResponse response) {
                    if (response.isOk()) {
                        GiftMessageList list = (GiftMessageList) response.getBaseData();
                        List<GiftMessageList.GiftMessageInfo> lastGiftMessages = list.getGiftMessageList();
                        if (lastGiftMessages != null && !lastGiftMessages.isEmpty()) {
                            lmvMeassages.setVisibility(View.VISIBLE);
                            marqueeView.setData(lastGiftMessages);
                            lmvMeassages.setAnimInAndOut(R.anim.top_in, R.anim.bottom_out);
                            lmvMeassages.setMarqueeFactory(marqueeView);
                            lmvMeassages.startFlipping();
                        }
                    }
                }
            });
    }

    /**
     * 初始化标题
     */
    private void onTitleInit() {
        setBackView();
        View baseTitleView = LayoutInflater.from(this).inflate(R.layout.f1_privatechatact_titleview, null);
        View baseTitleViewRight = LayoutInflater.from(this).inflate(R.layout.f1_privatechatact_titleview_right, null);
        setTitleCenterContainer(baseTitleView);
        setTitleRightContainer(baseTitleViewRight);
        base_title_title = (TextView) baseTitleView.findViewById(R.id.cus_top_title);
        net_top_title = (TextView) baseTitleView.findViewById(R.id.net_top_title);

        setNickName(name);
        if (MailSpecialID.customerService.getSpecialID() != whisperID) {//缘分小秘书
            setTitleRightImg(R.drawable.f1_user_ico, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    UIShow.showUserOtherSetAct(PrivateChatAct.this, whisperID, null, CenterConstant.USER_SET_FROM_CHAT);
                }
            });
        }
    }

    private void setNickName(String nickName) {
        String str = whisperID + "";

        if (whisperID == MailSpecialID.customerService.getSpecialID()) {
            str = MailSpecialID.customerService.getSpecialIDName();
        }

        if (!TextUtils.isEmpty(nickName)) {
            str = nickName;
        }

        if (base_title_title != null) {
            base_title_title.setText(str.length() > 10 ? (str.substring(0, 10)) : (str));
        }
    }

    private void initView() {
        onTitleInit();

        // 网络状态提示
        RelativeLayout netStatusLayout = (RelativeLayout) findViewById(R.id.netStatusLayout);
        offNetPanel = new OffNetPanel(this, netStatusLayout);
        netStatusLayout.addView(offNetPanel);

        privateChat = (ChatViewLayout) findViewById(R.id.privatechat_view);
        privateChat.getChatAdapter().setWhisperId(whisperID);
        lmvMeassages = (LMarqueeView) findViewById(R.id.privatechat_lmv_messages);
        marqueeView = new GiftMessageInfoView(this);

        initLastGiftList();

        // 获取最新用户信息回调
        privateChat.getChatAdapter().setOnUserInfoListener(new ChatInterface.OnUserInfoListener() {
            @Override
            public void onComplete(UserLight infoLightweight) {
                if (infoLightweight != null && whisperID == infoLightweight.getUid()) {
                    setNickName(infoLightweight.getNickname());

//                    kf_id = infoLightweight.getKf_id();
                    if (kf_id != 0 || MailSpecialID.customerService.getSpecialID() == whisperID) {
                        privateChat.getChatAdapter().onDataUpdate();
                    }
                }
            }
        });

        if (MailSpecialID.customerService.getSpecialID() != whisperID) {
            initFollow();
        }

        //状态栏 + 标题 +（关注TA、查看手机）// （去掉滚动条高度） 高度
        PSP.getInstance().put(Constant.PRIVATE_CHAT_TOP_H, UIUtil.getViewHeight(getTitleView()) + ScreenUtils.getStatusBarHeight(this));
    }

    /**
     * 获取用户详情
     */
    private void initFollow() {
        ModuleMgr.getCenterMgr().reqOtherInfo(whisperID, new RequestComplete() {
            @Override
            public void onRequestComplete(HttpResponse response) {
                if (!response.isOk()) return;
                UserDetail userDetail = (UserDetail) response.getBaseData();
                kf_id = userDetail.getKf_id();
                name = userDetail.getNickname();
                setNickName(userDetail.getNickname());
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // 更新备注名
        if (requestCode == CenterConstant.USER_SET_REQUEST_CODE) {
            switch (resultCode) {
                case CenterConstant.USER_SET_RESULT_CODE:
                    String remark = data.getStringExtra("remark");
                    setNickName(TextUtils.isEmpty(remark) ? name : remark);
                    break;
            }
        }
    }

    @Override
    public void onMessage(String key, Object value) {
        switch (key) {
            case MsgType.MT_Chat_Clear_History:
                long tmpID = (long) value;
                if (privateChat != null && whisperID == tmpID) {
                    privateChat.getChatAdapter().clearHistory();
                }
                break;
            case MsgType.MT_Chat_Can:
                if (ModuleMgr.getCenterMgr().getMyInfo().isMan() && value != null && value instanceof Boolean) {
                    boolean b = (boolean) value;
                    if (!b) {
                        checkIsCanSendMsg();
                    }
                }
                break;

            case MsgType.MT_MyInfo_Change://更新个人资料
                if (ModuleMgr.getCenterMgr().getMyInfo().isMan() && ModuleMgr.getCenterMgr().getMyInfo().isVip()) {//男
                    privateChat.getChatAdapter().showIsCanChat(true);
                }
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        MsgMgr.getInstance().detach(this);
        privateChat.getChatAdapter().detach();
    }

    @Override
    protected void onResume() {
        super.onResume();
        reqChatInfo();
    }
}